<template>
  <div class="params">
    <!-- 面包屑区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">商品管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片试图区域 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数" type="warning" :closable="false" show-icon></el-alert>

      <!-- 选择商品分类区域 -->
      <el-row>
        <el-col>
          <span>选择商品分类：</span>
          <!-- 级联选择框选择分类 -->
          <el-cascader
            v-model="selectKeys"
            clearable
            :options="categoriesList"
            :props="{ expandTrigger: 'hover',
                      value: 'cat_id',
                      label: 'cat_name',
                      children: 'children' }"
            @change="parentCategoriesChanged">
          </el-cascader>
        </el-col>
      </el-row>

      <!-- tabs 页面区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabsClick">
        <!-- 动态参数页面 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加动态参数列表 -->
          <el-button type="primary" :disabled="isBtnDisabled" @click="addDialogVisible = true">添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="tableData" border stripe v-show="selectKeys.length === 3">
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template v-slot="scope">
                <el-tag :key="item" closable v-for="(item, index) in scope.row.attr_vals"
                         @close="handleClose(index, scope.row)">
                  {{item}}
                </el-tag>
                <el-input class="input-new-tag" v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引行 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="editDialogClick(scope.row)">编辑</el-button>
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteDialogClick(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 添加静态属性 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="isBtnDisabled" @click="addDialogVisible = true">添加属性</el-button>

          <!-- 静态属性表格 -->
          <el-table :data="tableData" border stripe v-show="selectKeys.length === 3">
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template v-slot="scope">
                <el-tag :key="item" closable v-for="(item, index) in scope.row.attr_vals"
                         @close="handleClose(index, scope.row)">
                  {{item}}
                </el-tag>
                <el-input class="input-new-tag" v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue" ref="saveTagInput" size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引行 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="editDialogClick(scope.row)">编辑</el-button>
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteDialogClick(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>


    <!-- 添加 动态参数||静态属性 对话框 -->
    <el-dialog
      :title="activeName == 'many' ? '添加动态参数' : '添加静态属性'"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClose">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item :label="activeName == 'many' ? '动态参数' : '静态属性'" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureAddDialogVisible">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数 对话框 -->
    <el-dialog
      :title="activeName == 'many' ? '修改动态参数' : '修改静态属性'"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClose">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item :label="activeName == 'many' ? '动态参数' : '静态属性'" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureEditDialogVisible">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getCategoriesList } from 'network/goods_category'
import { getCategoriesAttributes, addCategoriesAttributes, editCategoriesAttributes, deleteCategoriesAttributes } from 'network/goods_params'

export default {
  name: "Params",
  data() {
    return {
      // 所有商品数据的列表
      categoriesList: [],

      // 选中的父级分类的Id数组
      selectKeys: [],

      // 被激活的 tabs 页面的名称
      activeName: 'many',

      // 保存 动态参数||静态属性 的数据列表
      tableData: [],

      // 按钮和添加 arrt_vals 之间的切换
      inputVisible: false,

      // 添加 动态参数||静态属性 对话框的显示和隐藏
      addDialogVisible: false,

      // 修改 动态参数||静态属性 对话框的显示和隐藏
      editDialogVisible: false,

      // 添加 参数||属性 的数据对象
      addForm: {
        attr_name: ''
      },

      // 修改 参数||属性 的数据对象
      editForm:{
      },

      // 添加 attr_vals 的绑定数据
      inputValue: '',

      // 添加数据表单的验证规则
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },

      // 修改数据表单的验证规则
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getCategoriesList()
  },

  computed: {
    // 判断是否是选中三级分类
    isBtnDisabled() {
      return this.selectKeys.length === 3 ? false : true
    },

    // 当前选中的三级分类的ID
    categoryId() {
      if(this.selectKeys.length === 3) 
        return this.selectKeys[2]
      return null
    }
  },
  methods: {
    // 获取所有商品数据的列表
    getCategoriesList() {
      getCategoriesList({type: 3}).then(res => {
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.categoriesList = res.data
        // console.log(this.categoriesList);
      }).catch(err => this.$message.error(err))
    },

    // 父级选择项发送改变触发这个函数 
    parentCategoriesChanged() {
      // 如果选中的不是三级分类
      // console.log(this.categoryId);
      if(this.selectKeys.length !== 3) {
        this.selectKeys = []
        return
      }
      getCategoriesAttributes(this.categoryId, this.activeName).then(res => {
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          // 控制文本框的显示与隐藏
          item.inputVisible = false
          // 文本框中输入的值为空
          item.inputValue = ''
          })
        this.tableData = res.data
        console.log(this.tableData);
      }).catch(err => this.$message.error(err))
    },

    // tabs 页面发生点击事件
    handleTabsClick() {
      this.parentCategoriesChanged()
    },

    // 监听 添加动态参数||静态属性 的点击事件
    editDialogClick(attrData) {
      this.editForm = attrData
      this.editDialogVisible = true
    },

    // 监听 删除动态参数||静态属性 的点击事件
    deleteDialogClick(attrId) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteCategoriesAttributes(this.categoryId, attrId).then(res => {
            if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
            this.$message.success(res.meta.msg)
            this.parentCategoriesChanged()
          }).catch(err => { this.$message.error(err) })
        }).catch(err => { this.$message.error(err) })
    },

    // 确认 添加 动态参数||静态属性
    sureAddDialogVisible() {
      this.$refs.addFormRef.validate(valid => {
        if(!valid) return
        addCategoriesAttributes(this.categoryId, { attr_name: this.addForm.attr_name, attr_sel: this.activeName }).then(res => {
          if(res.meta.status !== 201) return this.$message.error(res.meta.msg)
          this.$message.success(res.meta.msg)
          this.addDialogVisible = false
          this.parentCategoriesChanged()
        }).catch(err => { this.$message.error(err) })
      })
      
    },

    // 确认 修改  动态参数||静态属性
    sureEditDialogVisible() {
      this.$refs.editFormRef.validate(valid => {
        if(!valid) return
        editCategoriesAttributes( this.categoryId, 
                                  this.editForm.attr_id, 
                                  { attr_name: this.editForm.attr_name, 
                                    attr_sel: this.activeName }).then(res => {
          if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.$message.success(res.meta.msg)
          this.editDialogVisible = false
          this.parentCategoriesChanged()
        }).catch(err => { this.$message.error(err) })
      })
    },    

    // 监听 添加动态参数 对话框的关闭事件
    addDialogClose() {
      this.$refs.addFormRef.resetFields()
    },

    // 监听 修改动态参数 对话框的关闭事件
    editDialogClose() {
      this.$refs.editFormRef.resetFields()
    },

    // 文本框 失去焦点||按下了enter键 都会触发该事件
    handleInputConfirm(row) {
      console.log(row);
      if(row.inputValue.trim().length === 0) {
        row.inputValue = '' 
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = '' 
      row.inputVisible = false
      this.saveAttrVals(row)
    },

    // 将对 attr_vals 的操作， 保存到数据库 
    saveAttrVals(row) {
      editCategoriesAttributes( this.categoryId, 
                                row.attr_id, 
                                { attr_name: row.attr_name, 
                                  attr_sel: row.attr_sel,
                                  attr_vals: row.attr_vals.join(' ') }).then(res => {
          if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.$message.success(res.meta.msg)
        }).catch(err => { this.$message.error(err) })
    },

    // 点击按钮 展示文本输入框
    showInput(row) {
      row.inputVisible = true
      // $nextTick 方法作用， 当页面上元素被重新渲染之后才会执行回调函数中的代码
      this.$nextTick(() => {
        this.$refs.saveTagInput.focus();
      });
    },

    // 删除对应的删除可选项
    handleClose(index, row) {
      row.attr_vals.splice(index, 1)
      this.saveAttrVals(row)
    }
  }
}
</script>

<style>
  .el-card,
  .el-row,
  .el-table {
    margin-top: 20px;
  }

  .el-tag {
    margin: 5px;
  }

  .span {
    font-size: 18px;
  }

  .input-new-tag {
    width: 120px;
    margin-left: 10px;
  }
</style>